<?php

class Default_RequestController extends Zend_Controller_Action
{

    public $Session = null;

    public function init()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');   
        Zend_Session::start();
        $this->Session = new Zend_Session_Namespace ('Params');
    }

    public function indexAction()
    {
        $this->getResponse() 
             ->setHeader('Content-type', 'image/jpeg');

        $im = imagecreate (200,200);
        imagejpeg ($im);
        imagedestroy($im);
    }

    public function groupAction()
    {
        $this->_helper->layout->disableLayout();
            $this->getResponse() 
                 ->setHeader('Content-type', 'image/jpeg');
        $request          = $this->getRequest();  
        $groupName        = $request->getParam('name'); 
        $imageSize        = $request->getParam('size');  
        $newsGroup        = new Default_Model_Newsgroup;
        $newsGroup->Name  = $groupName;
        $groupPicture     = $newsGroup->GetRandom ($imageSize);
        
    }

    public function findgroupAction()
    {
        $this->_helper->layout->disableLayout();
        $request           = $this->getRequest();  
        $findParam         = $request->getParam('param'); 
        $targetURL         = '/index/search/param/' . strtolower($findParam);
        $message = $this->_helper->getHelper("FlashMessenger")->getMessages(); 
        if($message) $targetURL = $message[0];  
        $this->_redirector
                 ->gotoUrl($targetURL); 
    }

    public function watchAction()
    {
        $this->_helper->layout->disableLayout();
        $request    = $this->getRequest();  
        $ID         = $request->getParam('id'); 
        $queuePath  = QUEUE_DATA . "/{$ID}.queue";
        $queueState = "";
        if (file_exists($queuePath)) {
            $queueData   = file_get_contents($queuePath);
            unlink ($queuePath);
            echo $queueData;
            return; 
        } 
    }

    public function filterAction()
    {
        $this->_helper->layout->disableLayout();
        $request    = $this->getRequest();  
        $group      = $request->getParam('group'); 
        $page       = $request->getParam('page'); 
        $type       = $request->getParam('type');  
        $this->_redirector
                 ->gotoUrl("/group/{$group}/{$page}/{$type}"); 
    } 

    public function pictureAction()
    {
        $this->_helper->layout->disableLayout();
        $request          = $this->getRequest();  
        $this->groupname  = $request->getParam('name'); 
        $this->set        = $request->getParam('set');  
        $this->index      = $request->getParam('index');  
        $this->image      = $request->getParam('image');   
        $this->thumb      = $request->getParam('thumb');    
        $this->rect       = $request->getParam('rect');    
        $this->serve      = $request->getParam('serve');    

        if (isset($this->index)) { 
            $articleKey       = $this->index;  
            $base64Name       = base64_encode ($articleKey);
            $assetFolder      = DATA_PATH . "/asset";
            $groupFolder      = "{$assetFolder}/{$this->groupname}";
            $picturePath      = "{$groupFolder}/{$base64Name}";  
        }
        else if (isset($this->image)) { 
            $listObject  = $this->view->ArticleList($this->groupname);
            $set = $listObject->GetArticleSet($this->image);
            if (!$set) echo "Set {$this->image} not found!";
            $set->CheckPreview($this->groupname); 
            $picturePath = $set->image;  
        }
        else {

            return;
        } 

 if (!file_exists($picturePath)) {

        $lib  = new Default_Model_MediaIndex(true); 
        $lib->GetArticle($this->groupname, $articleKey); 
        $test = $lib->Article; 
    if ($test) $picturePath = $test['imageuri'];

}
            $this->getResponse()->setHeader('Content-type', 'image/jpeg');
            $thumb = new Default_Model_Picture;
        if (file_exists($picturePath)) { 

            if (isset($this->index) && !isset($this->thumb)) {
                echo file_get_contents($picturePath);
	        return; 
            }
            

            $thumb->Thumbnail ($picturePath,$this->thumb,$this->rect); 
        } else $thumb->Thumbnail (NULL,$this->thumb); #echo $picturePath . ' not found.';
    }

    public function bookmarkAction()
    {
        $this->_helper->layout->disableLayout();
        $request    = $this->getRequest();  
        $origin     = $request->getHeader ('referer'); 
        $groupname  = $request->getParam('group'); 
        $index      = $request->getParam('article'); 

        $m = new Default_Model_BookmarkManager;
        $ok = $m->Add($groupname, $index) ;
        if ($ok)
            $this->_redirector
                     ->gotoUrl($origin); 
        echo "Could not add bookmark! {$groupname}/{$index}<br/><a href='{$origin}'>Go Back</a>";
    }

    public function subscribeAction()
    {
        $this->_helper->layout->disableLayout();
        $request    = $this->getRequest(); 
        $groupname  = $request->getParam('group'); 
        $origin     = $request->getHeader ('referer'); 
        $m = new Default_Model_UserProfile;
        $m->Subscribe($groupname);

        $this->_redirector
                 ->gotoUrl($origin); 
    }

    public function joinAction()
    {
        unset ($this->Session->Type);
        unset ($this->Session->Search);
        unset ($this->Session->Saved);
        $request    = $this->getRequest(); 
        $groupname  = $request->getParam('groupname');  
        $start      = $request->getParam('start');  
        $renew      = $request->getParam('renew');  
        $count      = $request->getParam('count');  
        $DATA_URI   = DATA_PATH . "/index/{$groupname}.xml";
        $targetURL  = "/request/pagegroup/groupname/{$groupname}/pagenumber/1";

        $message = $this->_helper->getHelper("FlashMessenger")->getMessages(); 
        if($message){
            $this->_helper->layout->setLayout('ios');
            $this->view->links = array(array('text'=>'Loading...')); 
            $targetURL = $message[0];  
        }

        if (is_numeric($renew)) {
            $newsServer  = new Default_Model_NewsServer;
            $groupObject = $newsServer->groups[$groupname]; 
            $groupObject->sync(); 
            $groupObject->Rejoin($renew);  
            $this->_redirector
                  ->gotoUrl($targetURL);  
            return;
        }

        if (file_exists($DATA_URI) && $renew!='renew' && !isset($count)) {
            $this->_redirector
                  ->gotoUrl($targetURL);  
            return;
        }

        $this->view->groupname = $groupname;
        $data = array ('groupname'  => $groupname,
                        'location'   => $DATA_URI,
                        'start'      => $start,
                        'renew'      => $renew,
                        'count'      => isset($count) ? $count : 25000,
                        'endpoint'   => 'queue.newsgroup' );

        $MSGKEY = 519059;  # TO DO: Config 
        $Queue = new  Default_Model_QueueManager($MSGKEY, $data); 
        $Queue->SendMessage($targetURL); 
    }

    public function pagegroupAction()
    {
        $request    = $this->getRequest(); 
        $groupname  = $request->getParam('groupname'); 
        $pagenumber = $request->getParam('pagenumber'); 
        $pagefilter = $this->Session->Type; 
        $pagesearch = $this->Session->Search; 
        $savedparam = $this->Session->Saved; 
        $pageasync  = $request->getParam('async');  

        $targetURL  = "/group/list/group/{$groupname}/page/{$pagenumber}";
        $data = array ('groupname'  => $groupname,
                        'pagenumber' => $pagenumber,
                        'saved'      => $savedparam,
                        'filter'     => $pagefilter,
                        'search'     => $pagesearch,
                        'endpoint'   => ARTICLE_CLIENT );

        $MSGKEY = 519059;  # TO DO: Config 
        $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
        $this->view->Key = $Queue->SendMessage(isset($pageasync)?NULL:$targetURL); 
        $this->view->groupname = $groupname;
        $this->view->page      = $pagenumber;
        if (isset($pageasync)) {
            $this->_helper->layout->disableLayout();
            echo $this->view->Key;
        } else if (is_array($this->Session->Persisted)) {
            echo $this->view->partial( "persist.phtml", array("Persisted"=>$this->Session->Persisted,
                                                            "groupname"=>$groupname));
        }
    }

    public function downloadAction()
    {
        $request    = $this->getRequest(); 
        $origin     = $request->getHeader('referer'); 
        $groupname  = $request->getParam('group'); 
        $key        = $request->getParam('key'); 

        $b = new Default_Model_BookmarkManager;
        $bookmark = $b->Find ($groupname, $key);
        $DATA_URI  = DATA_PATH . "/bookmark/{$bookmark->Path}";
        $bookmark->Populate ($DATA_URI);


        $key = array();
        foreach ($bookmark->Items as $pic) $key[] = $pic->id;

        $data = array ('groupname'  => $groupname,
                        'endpoint'   => ARTICLE_CLIENT, 
                        'article'    => implode('/', $key) );

        $MSGKEY = 519059;  # TO DO: Config 
        $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
        $Id     = $Queue->SendMessage($origin);   
            $this->view->Persist($Id, $pic->subject, $groupname, 'download of', $origin);  
            $this->_redirector
                  ->gotoUrl($origin);  
    }

    public function asyncAction()
    {
        $this->_helper->layout->disableLayout();

        $request    = $this->getRequest(); 
        $key        = $request->getParam('key'); 
        $item       = $request->getParam('item'); 
        $groupname  = $request->getParam('group');   
        $show       = $request->getParam('show');  
        if (!isset($item)) $item = $key; 

        $b = new Default_Model_BookmarkManager;
        $bookmark = $b->Find ($groupname, $key);
        $DATA_URI  = DATA_PATH . "/bookmark/{$bookmark->Path}";
        $bookmark->Populate ($DATA_URI);

        $startIndex = ($show - 1) * 8;  
        $picsonpage = array_slice ($bookmark->Items, $startIndex, 8);
        $keys = array();
        foreach ($picsonpage as $pic) $keys[] = $pic->id;

        $data = array ('groupname'  => $groupname,
                        'endpoint'   => ARTICLE_CLIENT, 
                        'article'    => implode('/', $keys) );         

        $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
        $Id     = $Queue->SendMessage();  
        echo $Id;
    }

    public function iconAction()
    {
        $this->_helper->layout->disableLayout();
        $request    = $this->getRequest(); 
        $ibutton    = $request->getParam('ibutton'); 
        $button     = $request->getParam('button'); 
        $caption    = $request->getParam('caption'); 
        $slide      = $request->getParam('slide'); 
        $group      = $request->getParam('group'); 
        $progress   = $request->getParam('progress'); 
        $arc        = $request->getParam('arc'); 
        $size       = $request->getParam('size'); 
        if (isset($slide)) { 
            $photo = new Default_Model_Picture;
            $temp  = explode (',', $slide);
            $photo->Slide($group, $temp[0], $temp[1]);
            return;
        }
        if (isset($arc)) { 
            $photo = new Default_Model_Picture;
            $photo->Arc($arc, $size);
            return;
        }
        if (isset($progress)) { 
            $photo = new Default_Model_Picture;
            $photo->Progress($progress);
            return;
        }
        if (isset($ibutton)) { 
            $photo = new Default_Model_Picture;
            $photo->iButton($button, $ibutton, $caption);
            return;
        }
        if (isset($button)) { 
            $photo = new Default_Model_Picture;
            $photo->Button($button, $caption);
            return;
        }
        $this->getResponse() 
             ->setHeader('Content-type', 'image/jpeg');
        $im = imagecreate (200,10);
        $hue = imagecolorallocate ($im, 0x8F,0xBC,0xDB);//E4CC
        imagefill ($im, $hue, 0, 0);
        imagejpeg ($im, "", 100);
        imagedestroy ($im);
    }

    public function galleryAction()
    {
        $request    = $this->getRequest(); 
        $groupname  = $request->getParam('group'); 
        $pagenumber = $request->getParam('page'); 
        $article    = $request->getParam('article'); 
        $index      = $request->getParam('index');   
        $media      = $request->getParam('media');   
 
        $targetURL  = "/article-gallery/view/group/{$groupname}/page/{$pagenumber}/article/{$article}/index/{$index}";
        if ($media == "media") { 
            $this->_redirector->gotoUrl($targetURL);  
            return;
        }

        $message = $this->_helper->getHelper("FlashMessenger")->getMessages(); 
        if($message){
            $this->_helper->layout->setLayout('ios');
            $this->view->links = array(array('text'=>'Loading...')); 
            $targetURL = $message[0];  
        }

        $data = array ('groupname'  => $groupname,
                        'endpoint'   => ARTICLE_CLIENT, 
                        'article'    => $index);

        $MSGKEY = 519059;  # TO DO: Config 
        $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
        $Id     = $Queue->SendMessage($targetURL);//(is_numeric($show) ? NULL : $targetURL);  

        $this->view->Key     = $Id; 
        $this->view->group   = $groupname; 
        $this->view->article = $article; 
        $this->view->index   = $index; 
    }

    public function fullsearchAction()
    {
        $request    = $this->getRequest(); 
        $param      = $request->getParam('param'); 
        $persist    = $request->getParam('persist'); 
        $unpersist  = $request->getParam('unpersist'); 
        $savename   = $request->getParam('save'); 
        $groupname  = $request->getParam('groupname');  

        if (isset($unpersist)) {
            $this->_helper->layout->disableLayout();
            echo $this->view->Persist($unpersist); 
            return;
        } 

        if (isset($persist)) {
            $this->view->Persist($persist, $param, $groupname); 
            $this->_redirector
                  ->gotoUrl("/request/pagegroup/groupname/{$groupname}/pagenumber/1");  
        } 

        if (isset($savename)) {
            $this->Session->Saved = $savename;
            $this->_redirector
                  ->gotoUrl("/request/pagegroup/groupname/{$groupname}/pagenumber/1");  
        } 

        $data = array ('groupname'  => $groupname,
                        'endpoint'   => 'queue.thread.search', 
                        'param'      => $param);

        $MSGKEY = 519059;  # TO DO: Config 
        $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
        $Id     = $Queue->SendMessage("/request/fullsearch/save/{$param}/groupname/{$groupname}");   

        $this->view->groupname = $groupname;
        $this->view->param     = $param;
        $this->view->id        = $Id; 
        $message = $this->_helper->getHelper("FlashMessenger")->getMessages(); 
        if($message) {
            $this->view->Persist($Id, $param, $groupname);  
            $this->_redirector
                  ->gotoUrl(sizeof($message) > 1 ? $message[1] : $message[0]);  
        }    
    } 


    public function sabAction()
    {
        $request    = $this->getRequest(); 
        $origin     = $request->getHeader('referer'); 
        $savedparam = $this->Session->Saved; 
        $groupname  = $request->getParam('groupname');  
        $index      = $request->getParam('index');  
        $id         = $request->getParam('id');  
        $async      = $request->getParam('async');  



        $g = $this->view->ArticleList($groupname);
        $articles = $g->GetArticleSet($index, true);
        $articles->CheckPreview($groupname);
        $this->view->exist = false;
        foreach ($articles->items as $item) {
            $this->view->exist = $this->view->exist || (strpos ($item->id, $id)!==false &&
                                                   $item->media); 
        }

        if ($this->view->exist && isset($async)) {
             $this->_helper->layout->disableLayout();
             echo "OK"; 
        }
        else {

            $DataURI    = DATA_PATH . "/index/{$groupname}.xml";
            if (isset($savedparam) && strlen($savedparam) > 0) {
                $DataURI = DATA_PATH . "/search/{$groupname}/{$savedparam}.xml";  
            }  


            $data = array ('groupname'  => $groupname,
                            'endpoint'   => 'queue.sab', 
                            'filename'   => $DataURI, 
                            'index'      => $index, 
                            'article'    => $id);

            $MSGKEY = 519059;  # TO DO: Config 
            $Queue  = new  Default_Model_QueueManager($MSGKEY, $data); 
            $Id     = $Queue->SendMessage(isset ($async) ? NULL : $origin);  

 
            if (isset($async)){
                $this->_helper->layout->disableLayout();
                echo $Id;   
            }
            else {

                $target  = $origin;
                $message = $this->_helper->getHelper("FlashMessenger")->getMessages(); 
                if($message) $target = $message[0];

                unset ($this->Session->Persisted);
                $this->view->Persist($Id, $articles->subject, $groupname, 'Downloading', $target, $id);  
                $this->_redirector->gotoUrl($origin);  
            }
            $this->view->async   = $async; 
            $this->view->group   = $groupname; 
            $this->view->path    = $DataURI; 
        }
    }

}





























